package com.hjt.gulimall.ware.controller;

import com.hjt.common.exception.ErrorCodeEnum;
import com.hjt.common.exception.NoStockException;
import com.hjt.common.to.order.WareLockTo;
import com.hjt.common.to.ware.SkuHasStockTo;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.R;
import com.hjt.gulimall.ware.entity.WareSkuEntity;
import com.hjt.gulimall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;



/**
 * 商品库存
 *
 * @author huangjingtai
 * @email 970075985@qq.com
 * @date 2021-09-14 15:03:39
 */
@RestController
@RequestMapping("ware/waresku")
public class WareSkuController {
    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 锁定sku库存
     * 库存自动解锁
     * 1）下单成功，没有支付自动取消或者用户手动取消，都要解锁
     * 2）库存锁定成功，但是下单中后续步骤失败，订单回滚，也要解锁库存
     * @return
     */
    @PostMapping("/lock")
    public R lockSku(@RequestBody WareLockTo wareLockTo) {
        try {
            boolean result = wareSkuService.lock(wareLockTo);
            return R.ok();
        } catch (NoStockException noStockException) {
            noStockException.printStackTrace();
            return R.error(ErrorCodeEnum.NO_STOCK_EXCEPTION.getCode(), ErrorCodeEnum.NO_STOCK_EXCEPTION.getMessage());
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("ware:waresku:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = wareSkuService.queryPageWithCondition(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("ware:waresku:info")
    public R info(@PathVariable("id") Long id){
		WareSkuEntity wareSku = wareSkuService.getById(id);

        return R.ok().put("wareSku", wareSku);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("ware:waresku:save")
    public R save(@RequestBody WareSkuEntity wareSku){
		wareSkuService.save(wareSku);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("ware:waresku:update")
    public R update(@RequestBody WareSkuEntity wareSku){
		wareSkuService.updateById(wareSku);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("ware:waresku:delete")
    public R delete(@RequestBody Long[] ids){
		wareSkuService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 查询sku是否有库存
     * @param skuIdList sku的id列表
     * @return
     */
    @PostMapping("/hastStock")
    public R getSkuHasStock(@RequestBody List<Long> skuIdList) {

       List<SkuHasStockTo> skuHasStockToList = wareSkuService.querySkuHasStock(skuIdList);
       return R.ok().setData(skuHasStockToList);
    }

}
